﻿@using DiarySocial
@model DiarySocial.ViewModels.TimeLineWidgetVM
@{
    int userId = WebSecurity.GetUserId(User.Identity.Name);
}
<!-- Timeline -->
<div class="timeline comment-list">
    <article class="timeline-item alt" id="post-new-diary-cotainer">
        <!-- Editer for post new diary -->
        <div class="timeline-caption">
            <section class="panel panel-default">
                <div>
                    <span class="arrow right"></span>
                    <span class="timeline-icon"><i class="fa fa-plus time-icon bg-primary"></i></span>
                    <span class="timeline-date">
                        <i class="fa fa-clock-o"></i>
                        now
                    </span>
                </div>
                <form action="@Url.Action("QuickPost", "Diary")" method="post" data-bind="submit: submitPost" class="quick-post-form">
                    @Html.AntiForgeryToken()
                    @Html.TextAreaFor(m => m.Post.Body, new { @class = "form-control no-border", @rows = "3", @placeholder = "What did you do...", data_bind = "textInput: post.body" })
                    @*<textarea name="Body" class="" rows="3" placeholder="What did you do..."></textarea>*@
                    <footer class="panel-footer bg-light lter">
                        <button class="btn btn-info pull-right btn-sm" type="submit">POST</button>
                        <div class="btn-group m-r pull-right">
                            <button data-toggle="dropdown" class="btn btn-sm btn-default dropdown-toggle">
                                <span class="dropdown-label">Friend</span>
                                <span class="caret"></span>
                            </button>
                            <ul class="dropdown-menu dropdown-select">
                                <li class="">
                                    <a href="#">
                                        <i class="fa fa-globe"></i>
                                        <input type="radio" name="privacy">Public
                                    </a>
                                </li>
                                <li class="">
                                    <a href="#">
                                        <i class="fa fa-lock"></i>
                                        <input type="radio" name="privacy">Private
                                    </a>
                                </li>
                                <li class="active">
                                    <a href="#">
                                        <i class="fa fa-user"></i>
                                        <input type="radio" name="privacy" checked="">Friend
                                    </a>
                                </li>
                                <li class="disabled">
                                    <a href="#">
                                        <i class="fa fa-envelope-o"></i>
                                        <input type="radio" name="privacy" disabled>Invite
                                    </a>
                                </li>
                                <li class="disabled">
                                    <a href="#">
                                        <i class="fa fa-bullhorn"></i>
                                        <input type="radio" name="privacy" disabled>Anonymous
                                    </a>
                                </li>
                            </ul>
                        </div>
                        <ul class="nav nav-pills nav-sm">
                            @*<li class="disabled"><a href="#"><i class="fa fa-camera text-muted"></i></a></li>
                                <li class="disabled"><a href="#"><i class="fa fa-video-camera text-muted"></i></a></li>*@
                        </ul>
                    </footer>
                </form>
            </section>
        </div>
    </article>
    <!-- ko foreach: {data: items, as: 'posts'} -->
    <article class="timeline-item" data-bind="attr: {id: postId}, css: {'alt': $index() % 2 === 1}">
        <div class="timeline-caption">
            <section class="comment-body panel panel-default">
                <header class="panel-heading bg-white">
                    <span class="text" data-bind="html: privacyIcons"></span>
                    <a data-bind="attr: {href: author.authorLink, title: author.name}, text: author.name"></a>
                    <span class="text-muted m-l-sm pull-right">
                        <i class="fa fa-angle-down"></i>
                    </span>
                </header>
                <div class="panel-body">
                    <span class="arrow" ng-class="{ left: $index % 2 === 1, right: $index % 2 === 0 }"></span>
                    <span class="timeline-icon">
                        <a data-bind="attr: {href: author.authorLink, title: author.name}" class="thumb-sm avatar">
                            <img data-bind="attr: {src: author.avatar}" width="30" height="30" class="img-circle">
                        </a>
                    </span>
                    <span class="timeline-date">
                        <i class="fa fa-clock-o"></i>
                        <!-- ko text: time -->
                        <!-- /ko -->
                    </span>
                    <div class="more">
                        <div class="more-content" data-bind="text: body"></div>
                    </div>
                    <div class="comment-action">
                        <a href="#" class="btn btn-default btn-xs btn-like" data-bind="css: {'active': isLiked}, click: likeClick">
                            <i class="fa fa-star-o text-muted text"></i>
                            <i class="fa fa-star text-danger text-active" data-bind="visible: isLiked"></i>
                            Like
                        </a>
                        <a data-toggle="ajaxModal" class="btn btn-default btn-xs" data-bind="attr: {href: commentAction}">
                            <i class="fa fa-mail-reply text-muted"></i> Reply
                        </a>
                        <div class="small text-muted inline">
                            <a data-bind="visible: likeCount, event: {'shown.bs.popover': likeCountHoverOrClick}" href="#" class="like-count" tabindex="0">
                                <span data-bind="text: likeCount"></span>
                                <span> likes</span>
                            </a>
                            <div class="hidden liked-user-content">
                                <!-- ko if: !hasLoadLikedUser() -->
                                <i class="fa fa-spinner fa-spin fa-2x"></i>
                                <!-- /ko -->
                            </div>
                            <a data-toggle="ajaxModal" data-bind="attr: {href: commentAction}, visible: commentCount">
                                <span data-bind="text: commentCount"></span>
                                <span> comments</span>
                            </a>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </article>
    <!-- ko foreach: {data: comments, as: 'coms'} -->
    <article class="timeline-item comment-item comment-reply" data-bind="css: {'alt': $parentContext.$index() % 2 === 1}">
        <div class="timeline-caption">
            <a class="pull-left thumb-sm avatar" data-bind="attr: {href: commentAuthor.authorLink, title: commentAuthor.name}">
                <img data-bind="attr: {src: commentAuthor.avatar}" alt="">
            </a>
            <section class="comment-body panel panel-default text-sm">
                <div class="panel-body more">
                    <div class="more-content">
                        <span class="text-muted m-l-sm pull-right">
                            <i class="fa fa-clock-o"></i>
                            <!-- ko text: time -->
                            <!-- /ko -->
                        </span>
                        <a data-bind="attr: {href: commentAuthor.authorLink, title: commentAuthor.name}, text: commentAuthor.name"></a>
                        <span>: </span>
                        <span data-bind="text: text"></span>
                    </div>
                </div>
            </section>
        </div>
    </article>
    <!-- /ko -->
    <!-- /ko -->
    <div class="timeline-footer">
        <div class="wrapper">
        </div>
    </div>
</div>
@Html.Script(
    @<script type="text/javascript">
        // binding
        var data = @JavaScriptConvert.SerializeObject(Model);
        var AuthorVm = function(author) {
            var selfAuthor = this;
            selfAuthor.avatar = ko.observable(author.avatar);
            selfAuthor.name = ko.observable(author.name);
            selfAuthor.authorLink = ko.observable(author.authorLink);
        }
        var CommentVm = function(comment) {
            var selfComment = this;
            selfComment.id = ko.observable(comment.id);
            selfComment.text = ko.observable(comment.text);
            selfComment.time = ko.observable(comment.time);
            selfComment.commentAuthor = new AuthorVm(comment.commentAuthor);
        }
        var TimeLineItemVm = function(item) {
            var selfItem = this;
            selfItem.id = ko.observable(item.id);
            selfItem.body = ko.observable(item.body);
            selfItem.author = new AuthorVm(item.author);
            selfItem.likeCount = ko.observable(item.likeCount);
            selfItem.commentCount = ko.observable(item.commentCount);
            selfItem.isLiked = ko.observable(item.isLiked);
            selfItem.comments = ko.observableArray(ko.utils.arrayMap(item.comments, function(comment) {
                return new CommentVm(comment);
            }));
            selfItem.privacy = ko.observable(item.privacy);
            selfItem.privacyIcons = ko.computed(function() {
                switch (selfItem.privacy()) {
                    case 0:
                        return '<i class="fa fa-lock"></i>';
                    case 1:
                        return '<i class="fa fa-globe"></i>';
                    case 2:
                        return '<i class="fa fa-user"></i>';
                    case 3:
                        return '<i class="fa fa-envelope-o"></i>';
                    case 4:
                        return '<i class="fa fa-bullhorn"></i>';
                    default:
                        return "";
                }
            });
            selfItem.time = ko.observable(item.time);
            selfItem.postId = ko.computed(function() {
                return 'post-id-' + selfItem.id();
            }, this);
            selfItem.likeClick = function(data, event) {
                likePost(data, event);
            };
            selfItem.hasLoadLikedUser = ko.observable(false);
            selfItem.likeCountHoverOrClick = function(data, event) {
                showLikedUsers(data, event);
            };
            selfItem.commentAction = ko.computed(function() {
                return "@Url.Action("Comment", "Diary")/" + selfItem.id();
            });
        }

        var ViewModelVm = function(data) {
            var self = this;
            self.items = ko.observableArray(ko.utils.arrayMap(data.items, function(item) {
                return new TimeLineItemVm(item);
            }));
            self.post = new TimeLineItemVm(data.post);
            self.lastId = ko.computed(function() {
                return self.items.length > 0 ? data.items[0].id : 0;;
            });
            self.submitPost = function(formElement) {
                var body = self.post.body();
                if (body != null && body.trim() != '') {
                    self.post.time(new Date());
                    var newObject = new TimeLineItemVm(ko.toJS(self.post));
                    self.items.unshift(newObject);
                    self.post.body(null);
                    submitNewPost(body);
                }
            }
        }
        var viewModel = new ViewModelVm(data);
        ko.applyBindings(viewModel);
        // when click like button
        function toggedLikeButton(current) {
            current.isLiked(!current.isLiked());
            if (current.isLiked()) {
                current.likeCount(current.likeCount()+1);
            } else {
                current.likeCount(current.likeCount()-1);
            }
        }
        function likePost(current, event) {
            toggedLikeButton(current);
            $.ajax({
                url: "@Url.Action("Like", "Diary")",
                type: "POST",
                dataType: "json",
                data: {
                    id: current.id(),
                    isLike: current.isLiked()
                },
                beforeSend: function() {
                    $(event.currentTarget).addClass('disabled');
                },
                success: function(data) {
                    var success = data.success;
                    if (success) {
                        current.isLiked(data.like);
                        current.likeCount(data.likeCount);
                    } else {
                        toggedLikeButton(current);
                    }
                },
                error: function() {
                    toggedLikeButton(current);
                },
                complete: function() {
                    $(event.currentTarget).removeClass('disabled');
                    current.hasLoadLikedUser(false);
                }
            });
        };
        // when click like count link or hover like count link: show liked users
        function showLikedUsers(current, event) {
            if (current.likeCount() > 0 && !current.hasLoadLikedUser()) {
                var html = '<li>error</li>';
                $.ajax({
                    url: "@Url.Action("GetLikedUsers", "Diary")",
                    type: "POST",
                    dataType: "json",
                    data: {
                        id: current.id()
                    },
                    success: function(data) {
                        var success = data.success;
                        if (success) {
                            html = '<ul class="list-unstyled">';
                            if (data.likeCount === 0) {
                                html = html + '<li>0 user</li>';
                            } else {
                                $.each(data.likedUsers, function(index, element) {
                                    html = html + '<li><a href="' + element.AuthorLink + '" title="' + element.Name + '">' + element.Name + '</a></li>';
                                });
                            }
                            html = html + '</ul>';
                            $(event.currentTarget).parent().find(".liked-user-content").html(html);
                            current.hasLoadLikedUser(true);
                        }
                    },
                    complete: function() {
                        $(event.currentTarget).next().find('.popover-content').html('<div class="liked-user-content">' + html + '</div>');
                    }
                });
            }
        }

        // when submit post click
        function restorePostForm() {
            //viewModel.post = viewModel.items.shift();
        }
        function submitNewPost(body) {
            $.ajax({
                url: "@Url.Action("QuickPost", "Diary")",
                type: "post",
                dataType: "json",
                data: {
                    body: body,
                    privacy: 2,
                    lastId: viewModel.lastId()
                },
                beforeSend: function() {
                    $("form.quick-post-form button[type=submit]").addClass('disabled').html('POST <i class="fa fa-spinner fa-spin"></i>').fadeIn(200);
                },
                success: function(data) {
                    var success = data.success;
                    if (success) {
                        var diary = viewModel.items.shift();
                        var diaryId = data.id;
                        diary.id(diaryId);
                        viewModel.items.unshift(diary);
                    } else {
                        alert("Error when post new post, please try again");
                        console.log("success = false");
                        restorePostForm();
                    }
                },
                error: function(xhr) {
                    alert("Error when post new post, please try again");
                    console.log("error:");
                    console.log(xhr.responseText);
                    restorePostForm();
                },
                complete: function() {
                    $("form.quick-post-form button[type=submit]").html("POST").removeClass('disabled');
                }
            });
        }
        function toCamel(o) {
            var build, key, destKey, value;

            if (o instanceof Array) {
                build = [];
                for (key in o) {
                    value = o[key];

                    if (typeof value === "object") {
                        value = toCamel(value);
                    }
                    build.push(value);
                }
            }
            else {
                build = {};
                for (key in o) {
                    destKey = (key.charAt(0).toLowerCase() + key.slice(1) || key).toString();
                    value = o[key];
                    if (typeof value === "object") {
                        value = toCamel(value);
                    }

                    build[destKey] = value;
                }
            }
            return build;
        };
        $(document).ready(function() {
            // ko binding
            $('.like-count').popover({
                html: true,
                content: function() {
                    return $(this).next(".liked-user-content").html();
                },
                placement: "auto top",
                trigger: "focus"
            });
            $(window).scroll(function() {
                if($(window).scrollTop() + $(window).height() == $(document).height()) {
                    alert("bottom!");
                    // getData();
                }
            });
        });
    </script>
                                                        )